package com.example.netty.bio;

import com.example.netty.tomcat.http.GPServlet;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

/**
 * @author gorkr
 * @date 2022/07/21 10:40
 **/
public class GPTomcat {

    private int port = 8080;
    private ServerSocket server;
    private Map<String, GPServlet> servletMapping = new HashMap<String, GPServlet>();

    private Properties webxml = new Properties();

    private void init() {
        // 加载Web.xml文件，同时初始化ServletMapping对象
        try {
            // 读取web.properties
            String WEB_INF = this.getClass().getResource("/").getPath();
            System.out.println("web_inf : " + WEB_INF);
            FileInputStream fis = new FileInputStream(WEB_INF + "web.properties");
            webxml.load(fis);

            for (Object k :
                    webxml.keySet()) {

                String key = k.toString();
                if (key.endsWith(".url")) {
                    String serveletName = key.replaceAll("\\.url$", "");

                    // 获取配置里的两个属性
                    String url = webxml.getProperty(key);
                    String className = webxml.getProperty(serveletName + ".className");

                    // 单实例，多线程
                    GPServlet obj = (GPServlet) Class.forName(className).newInstance();
                    servletMapping.put(url,obj);

                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 就绪阶段
    public void start(){
        // 加载配置文件 初始化serveletMapping
        init();
        try {
            server = new ServerSocket(this.port);
            System.out.println("GPTomacat已启动，监听的端口是：" + this.port);

            // 等待用户请求
            while(true){
                Socket client = server.accept();
                // http请求，发送的数据就是字符串--有规律的字符串(符合http)
                process(client);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void process(Socket client) throws Exception{
        InputStream is = client.getInputStream();
        OutputStream os = client.getOutputStream();

        GPRequest request = new GPRequest(is);
        GPResponse response = new GPResponse(os);

        String url = request.getUrl();

        if(servletMapping.containsKey(url)){
            servletMapping.get(url).service(request,response);
        }else {
            response.write("404 not found");
        }

        os.flush();
        os.close();

        is.close();
        client.close();

    }

    public static void main(String[] args) {
        new GPTomcat().start();
    }

}
    